package com.dome.mvp.base;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;

import com.dome.mvp.BR;

import java.util.ArrayList;
import java.util.List;

/**
 * Time: 6/1/2021 8:52
 * Author: TAO
 * Description:
 */
public abstract class BaseAdapter<T, VDB extends ViewDataBinding> extends RecyclerView.Adapter<BaseViewHolder<VDB>> {

    private List<T> list;

    public BaseAdapter() {
        list = new ArrayList<>();
    }

    @NonNull
    @Override
    public BaseViewHolder<VDB> onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater from = LayoutInflater.from(parent.getContext());
        return new BaseViewHolder<VDB>(DataBindingUtil.inflate(from, getLayoutRes(), parent, false));
    }

    @LayoutRes
    protected abstract int getLayoutRes();

    @Override
    public void onBindViewHolder(@NonNull BaseViewHolder<VDB> holder, int position) {
        VDB binding = DataBindingUtil.getBinding(holder.itemView);
        binding.setVariable(BR.data, list.get(position));
        binding.executePendingBindings();
        onBind(holder, position, list.get(position));
    }

    protected abstract void onBind(@NonNull BaseViewHolder<VDB> holder, int position, @NonNull T t);

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    public void addData(List<T> list) {
        this.list.addAll(list);
        notifyDataSetChanged();
    }

    public void addData(T list) {
        this.list.add(list);
        notifyDataSetChanged();
    }

    public List<T> getList() {
        return list;
    }
}
